<script setup>

    /*********************************用户名密码登录 start********************************************/
    import { ref,reactive,onMounted} from 'vue'
    import axios  from 'axios'

    import { useRouter } from 'vue-router'

    import { ElMessage  } from 'element-plus';

    import { userStore } from '@/store/user.js'

    const router = useRouter();

    const userItemStore = userStore();


    // ref             操作 对象的时候 需要 .value
    // reactive        操作 对象数据的时候 可以直接操作  如果是对象 建议 reactive

    const loginForm = reactive({
        account: '',
        password: '',
        code: '',
        key: '',
    })

    //初始化表达校验

    const refLoginForm = ref(null);

    const codeUrl = ref(null);

    //不能点击
    const isButtonDisabled = ref(false);


    const rules = reactive({
        account: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
         password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
         ],
         code: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { min: 2, max: 2, message: '长度必须是2位', trigger: 'blur' }
        ]
    })

    const userLogin = ()=>{
        refLoginForm.value.validate(valid=>{
            //进行表达校验  (valid 校验结果为true 才可以提交数据 )
            if (valid){
                axios.post('/user/login',loginForm).then(resp=>{
                    console.log(resp.data);
                    //存储 token 和用户信息 浏览器的本地存储
                    //拿到 拿到 服务器返回token 信息
                    localStorage.setItem('token',resp.headers.authorization);
                    //user 对象转成json字符串
                    localStorage.setItem('user',JSON.stringify(resp.data));
                    //提示框
                    ElMessage.success("登录成功....")

                    //pinia 存储 用户信息
                    userItemStore.updateUser(resp.data)
                    userItemStore.updateLoginStatus(true)

                    //跳转
                    router.push("/")
                }).catch(err=>{
                    ElMessage.success("登录失败....")
                })
            }else{
                return false;
            }
            //不能点击
            isButtonDisabled.value = true;
            // 5秒后变得可用
            setTimeout(() => {
                isButtonDisabled.value = false;
            }, 5000);

        })
    }
    //获取验证码
    const getCaptcha = ()=>{
        axios.get('/user/code').then(resp=>{
            codeUrl.value = resp.data.base64Img;
            loginForm.key = resp.data.key;
        })
    }
    /*********************************用户名密码登录 end ********************************************/

    /********************************* 手机号码验证码登录 start ********************************************/

    const smsForm = reactive({
        telephone: '',
        code: ''
    });

    //手机表单校验
    const rulesPhone = reactive({
        telephone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur' }
        ],
        code: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
        ]
    })

    const activeName = ref("telephone");

    //表单对象初始化
    const refSmsForm = ref(null)

    //发送短信
    const sendSms = ()=>{
        //验证手机号是否正确
        refSmsForm.value.validateField('telephone', result => {
             //result 表单校验通过为 true 发送短信
            if (result){
                axios.get(`/user/sendSms/${smsForm.telephone}`).then(resp=>{
                    //发送短信成功
                    const msg = resp.data;
                    ElMessage.success(msg);
                }).catch(err=>{
                    ElMessage.error("短信获取发送失败重新发送....");
                })
            }else{
              return false;
            }
        })
    }

    //短信登录
    const smsLogin = ()=>{
        refSmsForm.value.validate(valid=>{
            if (valid){
                //发送表单数据
                axios.post(`/user/smsLogin`,smsForm).then(resp=>{
                    //拿到数据
                    const user = resp.data;
                    //存储 token 和用户信息 浏览器的本地存储
                    //拿到 拿到 服务器返回token 信息
                    localStorage.setItem('token',resp.headers.authorization);
                    //user 对象转成json字符串
                    localStorage.setItem('user',JSON.stringify(resp.data));
                    //提示框
                    ElMessage.success("登录成功....")

                    //pinia 存储 用户信息
                    userItemStore.updateUser(resp.data)
                    userItemStore.updateLoginStatus(true)
                    //跳转
                    router.push("/")
                });
            }else{
                return false;
            }
        })
    }
    /********************************* 手机号码验证码登录 end ********************************************/


    onMounted(()=>{
        //初始化验证码
        getCaptcha();
    })


</script>

<template>
    <div class="login-container">
        <el-tabs v-model="activeName" type="border-card">
            <el-tab-pane label="用户名登录" name="userName">
                <el-card class="card">
                    <h2 class="title">蜗牛书城用户登录</h2>
                    <el-form ref="refLoginForm" :model="loginForm"
                             class="login-form"
                             :rules="rules" label-position="left"
                             label-width="80px">
                        <el-form-item label="用户名：" prop="account">
                            <el-input v-model="loginForm.account" placeholder="请输入用户名"></el-input>
                        </el-form-item>
                        <el-form-item label="密码：" prop="password">
                            <el-input type="password"
                                      v-model="loginForm.password"
                                      placeholder="请输入密码"></el-input>
                        </el-form-item>
                        <el-form-item label="验证码：" prop="code">
                            <div class="form-item-container">
                                <el-input v-model="loginForm.code"
                                          maxlength="4"
                                          minlength="4"
                                          placeholder="验证码"
                                          style="width: 90px;">
                                </el-input>
                                <img :src="codeUrl"
                                     style="cursor: pointer; margin-left: 10px;"
                                     @click="getCaptcha()"
                                     title="看不清点击刷新"/>
                            </div>
                        </el-form-item>
                        <div class="login-btn-container">
                            <el-button style="width: 150px;" type="primary"
                                       @click="userLogin"
                                       :disabled="isButtonDisabled"
                                       icon="el-icon-user-solid">登录
                            </el-button>
                        </div>
                    </el-form>
                </el-card>
            </el-tab-pane>
            <el-tab-pane class="container" label="手机号登录" name="telephone">
                <el-form ref="refSmsForm" :model="smsForm"
                         class="login-form" :rules="rulesPhone"
                         label-position="left"
                         label-width="80px">
                    <el-form-item label="手机号：" prop="telephone">
                        <el-input v-model="smsForm.telephone"
                                  placeholder="请输入手机号">
                            <template #suffix>
                                <el-icon><Iphone /></el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="验证码：" prop="code">
                        <div class="form-item-container">
                            <el-input v-model="smsForm.code" maxlength="4"
                                      minlength="4" placeholder="验证码"
                                      style="width: 90px; margin-right: 10px;">
                            </el-input>
                            <el-button type="text"
                                       @click="sendSms">
                                <el-icon :size="20"><Message /></el-icon>
                                发送短信验证码
                            </el-button>
                        </div>
                    </el-form-item>
                    <div class="login-btn-container">
                        <el-button style="width: 150px;"
                                   type="primary" @click="smsLogin"
                                   icon="el-icon-user-solid">登录
                        </el-button>
                    </div>
                </el-form>
            </el-tab-pane>
        </el-tabs>

    </div>
</template>

<style scoped>
    .login-container {
        position: fixed;
        height: 100%;
        width: 100%;
        left: 0;
        background-image: linear-gradient(0, rgb(68, 68, 235), lightblue);
        display: flex;
        /* 水平居中对齐 */
        justify-content: center;
        /* 垂直居中对齐 */
        height: 100%;
    }

    .card {
        margin-top: 20px;
        width: 450px;
        height: 430px;
        padding: 15px;
    }

    .title {
        margin-top: 10px;
        font-size: 25px;
        text-shadow: 2px 2px 4px #888;
        text-align: center;
    }

    .login-form {
        max-width: 300px;
        margin: 0 auto;
    }

    .login-btn-container {
        text-align: center;
        margin-bottom: 30px;
    }

    .form-item-container {
        display: flex;
        align-items: flex-end;
    }
</style>